package com.guigu.controller;


import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.Result;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.pojo.*;
import com.guigu.service.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.OpenApiRoyaltyDetailInfoPojo;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.guigu.pojo.AlipayProperties;
import com.guigu.pojo.OrderPayment;
import com.guigu.pojo.Orders;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 出库单表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@RestController
@RequestMapping("/alipay")
public class PayController {

    @Autowired
    private PayService payService;

    @Autowired
    private PayDetailsService payDetailsService;

    @Autowired
    private ProductService productService;
    @PostMapping("/payReview")
    @ResponseBody
    public Page<Pay> payRevie(@RequestBody HashMap<String, Object> map){
        Page<Pay> payPage = payService.payReview(map);
        System.out.println(payPage);
        return payPage;
    }
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderPaymentService orderPaymentService;

    @PostMapping("/payReview2")
    @ResponseBody
    public Page<Pay> payRevie2(@RequestBody HashMap<String, Object> map){
        Page<Pay> payPage = payService.payReview2(map);
        System.out.println(payPage);
        return payPage;
    }

    @PostMapping("/review")
    @ResponseBody
    public Boolean review(@RequestBody HashMap<String, Object> map){
        System.out.println(map);
        String payOrderNumber = map.get("payOrderNumber").toString();
        System.out.println(payOrderNumber);
        Pay pay = payService.getPayBypayOrderNumber(payOrderNumber);
        boolean b = false;
        //拿到出库单id，修改商品库存数量
        Integer payId = pay.getPayId();
        List<PayDetails> payDetails = payDetailsService.getPayDetails2(payId);
        for (PayDetails payDetail : payDetails) {
            System.out.println(payDetail);
            Integer amount = payDetail.getAmount();
            System.out.println(amount);
            // 拿到商品id，修改商品库存数量
            Product product = productService.getById(payDetail.getProductId());
            product.setStock((int) (product.getStock() - amount));
            b = productService.saveOrUpdate(product);
        }
        Orders orders = ordersService.selectByOrderNo(pay.getOrderList());
        orders.setConveyTag("P001-2");
        boolean b1 = ordersService.saveOrUpdate(orders);

        pay.setChecker(map.get("reviewer").toString());
        pay.setCheckTime(new Date());
        pay.setCheckReason(map.get("reason").toString());
        pay.setCheckTag("S001-3");
        boolean a = payService.saveOrUpdate(pay);

        if(a == true && b == true){
            return true;
        }
        return false;
    }

    /**
     * 支付接口（使用 GET 请求接收订单号）
     * @param httpResponse 响应
     * @throws Exception 异常
     */
    @GetMapping("/pay")
    public void pay(@RequestParam("orderNo") String orderNo, HttpServletResponse httpResponse) throws Exception {
        System.out.println("接收到的订单号：" + orderNo);

        Orders orders = ordersService.selectByOrderNo(orderNo);
        if (orders == null) {
            System.out.println("订单不存在");
            return;
        }
        if (orders.getStatus().equals("K002-3")) {
            System.out.println("订单已支付");
            return;
        }
        // 构造支付宝支付请求
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGateway(),
                alipayProperties.getAppId(), alipayProperties.getPrivateKey(), FORMAT, CHARSET,
                alipayProperties.getPublicKey(), SIGN_TYPE);

        //创建request对象并设置支付参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());// 异步回调地址
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);// 订单号
        bizContent.put("total_amount", orders.getTotalPrice());// 订单金额
        bizContent.put("subject", "支付订单");// 订单标题
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");// 支付类型
        alipayRequest.setBizContent(bizContent.toString());
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());// 支付成功后回调地址


        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

    }

    /**
     * 支付宝支付成功的回调接口（POST 请求）
     * @param request 支付宝回调请求
     * @throws Exception 异常
     */
    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign,
                    alipayProperties.getPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                String tradeNo = params.get("out_trade_no");// 订单号
                String gmtPayment = params.get("gmt_payment");// 支付时间
                String alipayTradeNo = params.get("trade_no");// 支付宝交易号
                // 更新订单状态为已支付，设置支付信息
                Orders orders = ordersService.selectByOrderNo(tradeNo);
                orders.setPayTag("K002-3");
                ordersService.updateById(orders);
                OrderPayment orderPayment = orderPaymentService.getOneByOrderNumber(orders.getOrderNumber());
                orderPayment.setPaymentMethod(orders.getPayMethod());
                orderPayment.setPaymentStatus("K002-3");
                orderPayment.setPaymentTime(new Date());
                orderPayment.setAlipayOrderOn(alipayTradeNo);
                orderPaymentService.updateById(orderPayment);
            }
        }
    }

    /*
     *   向支付宝发起退款
     *
     */
    @GetMapping("/refund")
    public Object refund(@RequestParam("orderNo") String orderNo, HttpServletResponse httpResponse) throws Exception {
        System.out.println("接收到的订单号：" + orderNo);
        // 构造支付宝支付请求
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGateway(),
                alipayProperties.getAppId(), alipayProperties.getPrivateKey(), FORMAT, CHARSET,
                alipayProperties.getPublicKey(), SIGN_TYPE);
        // 创建request对象并设置退款参数
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        // 根据orderNo查订单金额
        Orders orders = ordersService.selectByOrderNo(orderNo);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("refund_amount", orders.getTotalPrice());
        bizContent.put("out_request_no", "HZ01RF001");
        bizContent.put("body", "订单取消");


        // 返回参数选项，按需传入
        JSONArray queryOptions = new JSONArray();
        queryOptions.add("refund_detail_item_list");
        bizContent.put("query_options", queryOptions);


        request.setBizContent(bizContent.toString());
        try{
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            System.out.println(response.getBody());
            if(response.isSuccess()){
                System.out.println("退款成功");
                return true;
            } else {
                System.out.println("退款失败");
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 查看支付订单状态
     *
     * @param orderNo
     * @return
     */
    @SneakyThrows
    @GetMapping("/selectPayList")
    public Integer selectPayList(@RequestParam("orderNumber") String orderNo) {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGateway(),
                alipayProperties.getAppId(), alipayProperties.getPrivateKey(), FORMAT, CHARSET,
                alipayProperties.getPublicKey(), SIGN_TYPE);
        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
//        更具自己的业务查询
        Orders orders = ordersService.selectByOrderNo(orderNo);
        OrderPayment oneByOrderNumber = orderPaymentService.getOneByOrderNumber(orderNo);
        if (Objects.isNull(orders)) {
//            订单号不存在
            return 1;
        }
        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(orders.getOrderNumber());
        // 设置查询选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("trade_settle_info");//交易结算信息
        queryOptions.add("fund_bill_list");//交易支付资金渠道
        model.setQueryOptions(queryOptions);
        // 设置支付宝交易号
        model.setTradeNo(oneByOrderNumber.getAlipayOrderOn());
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
//            这里做演示就直接丢给前端了
            System.out.println(response.getBody());
            return 2;
        } else {
//            第三方调用失败
            return 3;
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }

}

